package kr.saeildamil.project.secretary;

import java.util.ArrayList;
import kr.saeildamil.project.secretary.DB.DBHelper;
import kr.saeildamil.project.secretary.fragment.NewSchedule;
import kr.saeildamil.project.secretary.fragment.UpdateSchedult;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SlidingDrawer;
import android.widget.TextView;

public class Main extends Activity {
	String pickyear;
	String pickmonth;
	String pickday;
	static String mainDate;
	static String delDate;
	TextView date;
	TextView user;
	static ListView mainList;
	static ListView delList;
	Button delcomplete;
	LinearLayout linear;
	FrameLayout deleteframe;
	DBHelper dbHelper;
	SQLiteDatabase db;
	Today today;
	CheckBox check;
	SlidingDrawer drawer;
	Button add;
	Button del;
	ArrayList<Schedule> mainSchedule;
	ArrayList<Schedule> delSchedule;

	static int dbId;
	static String TAG="Main";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Window win=getWindow();
		win.requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);

		date=(TextView) findViewById(R.id.main_current_date);
		user=(TextView) findViewById(R.id.userinformation);
		deleteframe=(FrameLayout) findViewById(R.id.delete_frame);
		linear=(LinearLayout) findViewById(R.id.main_schedule);
		mainList=(ListView) findViewById(R.id.today_schedule);
		delList=(ListView) findViewById(R.id.delete_schedule);
		drawer=(SlidingDrawer) findViewById(R.id.main_slidingDrawer);
		add=(Button) findViewById(R.id.main_btn1);
		del=(Button) findViewById(R.id.main_btn2);
		
		today=new Today();
		mainDate=today.currentdate2;
		date.setText(mainDate);

		MainSchedule(mainDate);//DB에 있는 당일 스케쥴 읽어옴

		date.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				drawer.animateClose();
				int myear=Integer.parseInt(today.year);
				int mmonth=Integer.parseInt(today.month);
				int mday=Integer.parseInt(today.day);
				Log.d(TAG, "DatePickerDialog 초기값"+myear+"월"+mmonth+"년"+mday+"일");

				new DatePickerDialog(Main.this, dateListener, myear, mmonth-1, mday).show();
			}
		});
	}

	DatePickerDialog.OnDateSetListener dateListener=new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			pickyear=String.valueOf(year);
			pickmonth=String.valueOf(monthOfYear+1);
			pickday=String.valueOf(dayOfMonth);
			if(pickmonth.length()==1){
				pickmonth="0"+pickmonth;
			}
			if(pickday.length()==1){
				pickday="0"+pickday;
			}
			mainDate=pickyear+"년 "+pickmonth+"월 "+pickday+"일";
			Log.d(TAG, "DatePickerDialog 선택값"+mainDate);

			if(linear.getVisibility()==view.VISIBLE){
				MainSchedule(mainDate);
			}else if(deleteframe.getVisibility()==view.VISIBLE){
				DeleteSchedule(mainDate);
			}
		}
	};

	public void mOnClick(View v){
		switch (v.getId()) {
		case R.id.main_btn1://스케줄 추가(Newschedule fragment)
			FragmentManager fm=getFragmentManager();
			Fragment fragment=fm.findFragmentById(R.id.frame_newschedule);
			FragmentTransaction tr=fm.beginTransaction();
			NewSchedule news=new NewSchedule();
			if(fragment==null){
				drawer.animateClose();
				linear.setVisibility(View.INVISIBLE);
				tr.add(R.id.frame_newschedule, news, "newschedule");
				add.setBackgroundResource(R.drawable.updatecancle_btn);
				tr.commit();
			}else{
				linear.setVisibility(View.VISIBLE);
				add.setBackgroundResource(R.drawable.update_btn);
				tr.remove(fragment);
				tr.commit();
			}
			break;

		case R.id.main_btn2://스케줄 삭제
			if(linear.getVisibility()==View.VISIBLE){
				linear.setVisibility(View.INVISIBLE);
				if(deleteframe.getVisibility()==View.INVISIBLE){
					deleteframe.setVisibility(View.VISIBLE);
				}
				del.setBackgroundResource(R.drawable.deletecomplete_btn);
				delDate=date.getText().toString();
				DeleteSchedule(delDate);

			}else if(linear.getVisibility()==View.INVISIBLE){
				del.setBackgroundResource(R.drawable.delete_btn);
				dbHelper=new DBHelper(this);
				db=dbHelper.getWritableDatabase();

				Log.d(TAG, "delSchedule.size"+String.valueOf(delSchedule.size()));
				int listCount=delList.getChildCount();
				for(int i=0; i<listCount; i++){
					check=(CheckBox) delList.getChildAt(i).findViewById(R.id.checkBox);
					if(check.isChecked()){
						Log.d(TAG, "Checkedposition : "+i);
						Log.d(TAG, "delSchedule.get(i).getId() : "+delSchedule.get(i).getId());
						db.execSQL("DELETE FROM schedule WHERE _id='"+delSchedule.get(i).getId()+"'");
					}
				}
				dbHelper.close();
				startActivity(new Intent(this, Main.class));
			}
			break;

		case R.id.main_btn5:
			Intent intent=new Intent(this, Setup.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(intent);

		case R.id.yesterday:
			drawer.animateClose();
			int yesterday=Integer.parseInt(mainDate.substring(10, 12))-1;
			if(yesterday>0){
				String result=mainDate.substring(0, 10)+String.valueOf(yesterday)+mainDate.substring(12);
				mainDate=result;
				MainSchedule(mainDate);
			}
			break;

		case R.id.tomorrow:
			drawer.animateClose();
			int tomorrow=Integer.parseInt(mainDate.substring(10, 12))+1;
			if(tomorrow>0){
				String result=mainDate.substring(0, 10)+String.valueOf(tomorrow)+mainDate.substring(12);
				mainDate=result;
				MainSchedule(mainDate);
			}
			break;
		}
	}

	private void MainSchedule(String mainDate) {
		try {
			Cursor cursor;
			Cursor cursor2;
			date.setText(mainDate);
			dbHelper=new DBHelper(this);
			db=dbHelper.getReadableDatabase();
			cursor=db.rawQuery("SELECT * FROM user", null);

			while(cursor.moveToNext()){
				user.setText(cursor.getString(2)+cursor.getString(3)+cursor.getString(4)+cursor.getString(5));
			}
			cursor2=db.rawQuery("SELECT * FROM schedule WHERE date='"+mainDate+"' ORDER BY hour,minute;", null);

			Schedule obj;
			mainSchedule = new ArrayList<Schedule>();
			while(cursor2.moveToNext()){
				obj = new Schedule(cursor2.getInt(0), cursor2.getString(1), cursor2.getString(2)
						, cursor2.getString(3), cursor2.getString(4), cursor2.getString(5));
				mainSchedule.add(obj);
			}

			startManagingCursor(cursor2);

			SimpleCursorAdapter adapter=null;
			adapter=new SimpleCursorAdapter(this, R.layout.todayschedule
					, cursor2, new String[]{"date","hour","minute","task","detail"}
			,new int[]{R.id.schedule_date,R.id.schedule_hour
					,R.id.schedule_minute,R.id.schedule_task,R.id.schedule_detail});

			mainList.setAdapter(adapter);
			mainList.setDivider(new ColorDrawable(Color.BLUE));
			mainList.setDividerHeight(2);
			//adapter.setViewBinder(delViewBinder);

			mainList.setOnItemLongClickListener(updateListener);

			//cursor.close();
			//cursor2.close();
			dbHelper.close();
		} catch (SQLiteException e) {
			e.printStackTrace();
		}
	}

	private void DeleteSchedule(String delDate) {
		try {
			Cursor cursor;
			Cursor cursor2;
			date.setText(delDate);
			dbHelper=new DBHelper(this);
			db=dbHelper.getReadableDatabase();
			cursor=db.rawQuery("SELECT * FROM user", null);

			while(cursor.moveToNext()){
				user.setText("선택한 사용자 : "+cursor.getString(0)+cursor.getString(1)+cursor.getString(2)
						+cursor.getString(3)+cursor.getString(4)+cursor.getString(5));
			}
			cursor2=db.rawQuery("SELECT * FROM schedule WHERE date='"+delDate+"' ORDER BY hour,minute;", null);

			Schedule obj;
			delSchedule = new ArrayList<Schedule>();
			while(cursor2.moveToNext()){
				obj = new Schedule(cursor2.getInt(0), cursor2.getString(1), cursor2.getString(2)
						, cursor2.getString(3), cursor2.getString(4), cursor2.getString(5));
				delSchedule.add(obj);
			}

			startManagingCursor(cursor2);

			SimpleCursorAdapter adapter=null;
			adapter=new SimpleCursorAdapter(this, R.layout.deleteschedule
					, cursor2, new String[]{"date","hour","minute","task","detail"}
			,new int[]{R.id.delete_date,R.id.delete_hour
					,R.id.delete_minute,R.id.delete_task,R.id.delete_detail});

			delList.setAdapter(adapter);
			delList.setDivider(new ColorDrawable(Color.RED));
			delList.setDividerHeight(2);
			//adapter.setViewBinder(delViewBinder);

			delList.setOnItemClickListener(delItemListener);

			//cursor.close();
			//cursor2.close();
			dbHelper.close();
		} catch (SQLiteException e) {
			e.printStackTrace();
		}
	}

	OnItemClickListener delItemListener=new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int position,
				long arg3) {
			check=(CheckBox) delList.getChildAt(position).findViewById(R.id.checkBox);
			if(check.isChecked()){
				check.setChecked(false);
			}else{
				check.setChecked(true);
			}

		}
	};

	/*ViewBinder delViewBinder=new ViewBinder() {

		@Override
		public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
			// TODO Auto-generated method stub
			return false;
		}
	};*/

	OnItemLongClickListener updateListener=new OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View v,
				int position, long id) {
			Schedule update = mainSchedule.get(position);
			dbId = update.getId();
			Log.d(TAG, "OnItemLongClickListener position : "+position+"\n"+"dbId : "+dbId);

			FragmentManager fm=getFragmentManager();
			FragmentTransaction tr=fm.beginTransaction();
			UpdateSchedult dialog=new UpdateSchedult();
			dialog.setStyle(DialogFragment.STYLE_NORMAL, 0);
			dialog.show(fm, "updatedialog");
			return false;
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			AlertDialog.Builder dialog=new AlertDialog.Builder(this);
			dialog.setTitle("나비서");
			dialog.setMessage("프로그램을 종료하시겠습니까?");
			dialog.setIcon(R.drawable.ic_launcher);
			dialog.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					moveTaskToBack(true);
					finish();
				}
			});
			dialog.setNegativeButton("취소", null);
			dialog.show();
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	public int getDbId() {
		Log.d(TAG, "getDbId = "+dbId);
		return dbId;
	}

	public void setDbId(int dbId) {
		this.dbId = dbId;
	}

	public String getMainDate() {
		Log.d(TAG, "getMainDate = "+mainDate);
		return mainDate;
	}

	public void setMainDate(String mainDate) {
		this.mainDate = mainDate;
	}
}
